package biznussoft.metercor.lookup;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

import android.app.Dialog;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListView;
import android.widget.TextView;
import biznussoft.metercor.R;
import biznussoft.metercor.fragments.AccountsFragment;
import biznussoft.metercor.fragments.AccountsdetailsFragment;
import biznussoft.metercor.fragments.ContactDetailsFragment;
import biznussoft.metercor.fragments.NewERTDeviceInstallationFragment;
import biznussoft.metercor.fragments.NewJobsiteInspectionCheckListFragmnet;
import biznussoft.metercor.fragments.NewSurveyFragment;
import biznussoft.metercor.fragments.ServiceOrderDetailsFragment;
import biznussoft.metercor.fragments.ServiceOrderFragment;
import biznussoft.metercor.model.Bean_Class;
import biznussoft.metercor.model.ContactsModel;
import biznussoft.metercor.model.SiteModel;
import biznussoft.metercor.utils.Session;

public class AccountLookup implements OnItemClickListener {
	LookupAdapter adapter;
	public static ArrayList<ContactsModel> contactsList;
	public static ArrayList<SiteModel> siteList;
	Dialog lookupDialog;
	String strCategory;
	boolean isFiltered;
	private ArrayList<Bean_Class> data;
	private ArrayList<Bean_Class> filterList;
	private ListView lvLookup;
	private EditText etLookUp;
	private RestClient mClient;
	private Context mContext;

	public void accountLookupDetails(Context context, String category) {

		// mClient = client;
		strCategory = category;
		mContext = context;
		lookupDialog = new Dialog(context);
		lookupDialog.setContentView(R.layout.accountlookup);
		lookupDialog.setTitle("FieldService360");
		lvLookup = (ListView) lookupDialog
				.findViewById(R.id.lvAccountlookuplistview);
		etLookUp = (EditText) lookupDialog.findViewById(R.id.etFilteraccount);
		adapter = new LookupAdapter(AccountsFragment.list);
		lvLookup.setAdapter(adapter);
		etLookUp.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

				adapter.getFilter().filter(s);

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			public void afterTextChanged(Editable s) {

			}
		});

		lookupDialog.show();

		lvLookup.setOnItemClickListener(this);

	}

	class LookupAdapter extends BaseAdapter implements Filterable {

		private ValueFilter valueFilter;

		ArrayList<Bean_Class> mStringFilterList = new ArrayList<Bean_Class>();

		public LookupAdapter(ArrayList<Bean_Class> list) {
			data = list;
			mStringFilterList = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return data.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		class ViewHolder {
			public TextView name, age;
		}

		@Override
		public View getView(int position, View v, ViewGroup parent) {
			ViewHolder holder;
			if (v == null) {
				holder = new ViewHolder();
				LayoutInflater inflater = (LayoutInflater) mContext
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflater.inflate(android.R.layout.simple_list_item_1, null);
				holder.name = (TextView) v.findViewById(android.R.id.text1);
				v.setTag(holder);
			} else {
				holder = (ViewHolder) v.getTag();
			}

			Bean_Class b = data.get(position);
			holder.name.setText(b.getName());

			return v;
		}

		public Filter getFilter() {
			if (valueFilter == null) {

				valueFilter = new ValueFilter();
			}

			return valueFilter;
		}

		private class ValueFilter extends Filter {

			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
				FilterResults results = new FilterResults();

				if (constraint != null && constraint.length() > 0) {

					filterList = new ArrayList<Bean_Class>();

					for (int i = 0; i < mStringFilterList.size(); i++) {

						String mLastName = mStringFilterList.get(i).getName();
						if (mLastName.toLowerCase().contains(
								constraint.toString())) {
							filterList.add(mStringFilterList.get(i));

						}
					}
					results.count = filterList.size();
					results.values = filterList;
					isFiltered = true;
				} else {
					isFiltered = false;
					results.count = mStringFilterList.size();
					results.values = mStringFilterList;

				}

				return results;
			}

			@SuppressWarnings("unchecked")
			@Override
			protected void publishResults(CharSequence constraint,
					FilterResults results) {
				data = (ArrayList<Bean_Class>) results.values;

				notifyDataSetChanged();

			}

		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {

		switch (arg0.getId()) {
		case R.id.lvAccountlookuplistview:
			Bean_Class bean = data.get(position);
			/*
			 * if(strCategory.equalsIgnoreCase("Account")){
			 * AccountsdetailsFragment
			 * .etParentAccount.setText(bean.getName());}else{
			 * ContactDetailsFragment
			 * .etContactAccountName.setText(bean.getName()); }
			 * Session.sParentId=bean.getId();
			 */
			// ServiceOrderDetailsFragment.etAccount.setText(bean.getName());
			if (strCategory.equalsIgnoreCase("survey")) {
				NewSurveyFragment.etAccount.setText(bean.getName());
			} else {
				NewJobsiteInspectionCheckListFragmnet.etLocation.setText(bean
						.getName());
			}
			Session.sAccountId = bean.getId();

			try {/*
				 * String accounts =
				 * "Select Id,LastName from Contact where AccountId="
				 * +"'"+Session.sAccountId+"'";
				 * 
				 * RestRequest restRequest =
				 * RestRequest.getRequestForQuery(mContext
				 * .getString(R.string.api_version), accounts);
				 * 
				 * mClient.sendAsync(restRequest, new AsyncRequestCallback() {
				 * 
				 * @Override public void onSuccess(RestRequest request,
				 * RestResponse result) { try { JSONObject jsonObject1 = new
				 * JSONObject(result.asString()); JSONArray jsonArray =
				 * jsonObject1.getJSONArray("records");
				 * 
				 * contactsList = new ArrayList<ContactsModel>(); Gson _gson =
				 * new Gson(); for(int i=0; i< jsonArray.length(); i++) {
				 * if(!jsonArray.isNull(i)){ ContactsModel bean =
				 * _gson.fromJson(jsonArray.getString(i), ContactsModel.class);
				 * contactsList.add(bean); }
				 * 
				 * }
				 * 
				 * 
				 * } catch (Exception e) { onError(e); } }
				 * 
				 * @Override public void onError(Exception exception) {
				 * Toast.makeText(MainActivity.this,
				 * MainActivity.this.getString(
				 * SalesforceSDKManager.getInstance()
				 * .getSalesforceR().stringGenericError(),
				 * exception.toString()), Toast.LENGTH_LONG).show();
				 * EventsObservable
				 * .get().notifyEvent(EventType.RenditionComplete); } });
				 * 
				 * 
				 * 
				 * } catch (Exception e) {
				 * Log.i("NCS","Exception  2 is  :"+e.getMessage()); }
				 * 
				 * try{/* String accounts =
				 * "Select Id,Name from FConnect__site__c where FConnect__Customer__c="
				 * +"'"+Session.sAccountId+"'";
				 * 
				 * RestRequest restRequest =
				 * RestRequest.getRequestForQuery(mContext
				 * .getString(R.string.api_version), accounts);
				 * 
				 * mClient.sendAsync(restRequest, new AsyncRequestCallback() {
				 * 
				 * @Override public void onSuccess(RestRequest request,
				 * RestResponse result) { try {
				 * Log.i("NCS","FConnect__Customer__c  :"+result); JSONObject
				 * jsonObject1 = new JSONObject(result.asString()); JSONArray
				 * jsonArray = jsonObject1.getJSONArray("records");
				 * 
				 * siteList = new ArrayList<SiteModel>(); Gson _gson = new
				 * Gson(); for(int i=0; i< jsonArray.length(); i++) {
				 * if(!jsonArray.isNull(i)){ SiteModel bean =
				 * _gson.fromJson(jsonArray.getString(i), SiteModel.class);
				 * siteList.add(bean); }
				 * 
				 * }
				 * 
				 * 
				 * } catch (Exception e) { onError(e); } }
				 * 
				 * @Override public void onError(Exception exception) {
				 * Toast.makeText(MainActivity.this,
				 * MainActivity.this.getString(
				 * SalesforceSDKManager.getInstance()
				 * .getSalesforceR().stringGenericError(),
				 * exception.toString()), Toast.LENGTH_LONG).show();
				 * EventsObservable
				 * .get().notifyEvent(EventType.RenditionComplete); } });
				 */
			} catch (Exception e) {
				Log.i("NCS", "Exception  2 is  :" + e.getMessage());
			}

			lookupDialog.dismiss();
			break;

		default:
			break;
		}

	}
}
